﻿/*------------------------------------------------------------------
-- COPYRIGHT (C) 2010-2012  Atom
-- ALL RIGHTS RESERVED.
-- 兆尹科技
-- CREATE DATE: 2010/07/12
-- CREATE MAN:liujian	
-- 创建实例工厂类
-- MODIFY HISTORY:
-- MODIFY DATE:
-- MODIFY MAN:	
-- MODIFY DESC:
-- MODIFY DATE:
-- MODIFY MAN:	
-- MODIFY DESC:
---------------------------------------------------------------------*/
using System;
using System.Collections.Generic;

namespace Atom.Common
{
    /// <summary>
    /// 创建实例工厂
    /// </summary>
    public static class ObjectCreator
    {
        /// <summary>
        /// 创建实例
        /// </summary>
        /// <typeparam name="T">指定要创建的实例类型</typeparam>
        /// <returns>实例</returns>
        public static T Create<T>()
            where T : new()
        {
            return Create<T>(null);
        }

        /// <summary>
        /// 创建实例
        /// </summary>
        /// <typeparam name="T">指定要创建的实例类型</typeparam>
        /// <param name="initial">初始化实例</param>
        /// <returns>实例</returns>
        public static T Create<T>(Action<T> initial)
            where T : new()
        {
            T t = new T();
            if (initial != null)
            {
                initial(t);
            }
            return t;
        }

        /// <summary>
        /// 创建实例
        /// </summary>
        /// <param name="t">指定要创建的类型</param>
        /// <param name="parameters">参数</param>
        /// <returns>创建对象</returns>
        public static object Create(Type t, params object[] parameters)
        {
            return Activator.CreateInstance(t, parameters);
        }

        //字典保存单体实例
        private static Dictionary<Type, object> cacheSingletons = new Dictionary<Type, object>();
        //加锁对象
        private static object lockObj = new object();

        /// <summary>
        /// 创建单例
        /// </summary>
        /// <typeparam name="T">创建单例对象的类型</typeparam>
        /// <returns>对象的类型</returns>
        public static T CreateSingleton<T>()
            where T : class, new()
        {
            object instance = null;           

            if (!cacheSingletons.TryGetValue(typeof(T), out instance))
            {
                lock (lockObj)
                {
                    if (!cacheSingletons.TryGetValue(typeof(T), out instance))
                    {
                        instance = new T();
                        cacheSingletons.Add(typeof(T), instance);
                    }
                }
            }

            return instance as T;
        }
    }
}
